<template>
  <div class="myTask background">
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom:10px;">
      <el-breadcrumb-item><img style="width: 16px;vertical-align: middle;margin-right: 5px" src="@/assets/indexPage/location.png"/> <span style="font-weight:600;">
         我的任务
      </span></el-breadcrumb-item>
      <!-- <el-breadcrumb-item>
        <span style="font-weight:600;">
           我的任务
        </span>
      </el-breadcrumb-item> -->
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-form ref="formData" :inline="true" :model="formData" class="searchLine" label-width="100px" size="small">
            <el-form-item label="任务开始时间" class="searchItem">
              <el-date-picker
                v-model="formData.taskStartTime"
                size="small"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="searchItemWidth"
              >
              </el-date-picker>
            </el-form-item>
          <el-form-item property="taskId" label="任务编码">
            <el-select class="searchItemWidth" v-model="formData.taskNumber" placeholder="请选择任务编码" clearable filterable @change="taskNumberChange">
              <el-option v-for="item in taskNumberList" :label="item.inspectTaskCode" :value="item.inspectTaskCode" :key="item.inspectTaskCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item property="oriFileName" label="文件名称">
            <el-input placeholder="请输入文件名称" class="searchItemWidth" v-model="formData.oriFileName"></el-input>
          </el-form-item>
          <el-form-item property="remark" label="文件描述" v-if="showAllItems">
            <el-input placeholder="请输入文件描述" class="searchItemWidth" v-model="formData.remark"></el-input>
          </el-form-item>
          <el-form-item property="companyCode" label="单位名称" v-if="showAllItems">
            <el-select class="searchItemWidth" v-model="formData.companyCode" placeholder="请选择单位" @change="companyChange" clearable filterable>
              <el-option v-for="item in tree" :label="item.companyName" :value="item.companyCode"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item property="name" label="场站名称" v-if="showAllItems">
            <el-select class="searchItemWidth" v-model="formData.stationCode" placeholder="请选择场站" @change="stationChange" clearable filterable>
              <el-option v-for="item in stationList" :label="item.stationName" :value="item.stationCode" :key="item.stationCode"></el-option>
            </el-select>
          </el-form-item>
<!--            <el-form-item label="任务状态" class="searchItem" v-if="showAllItems">-->
<!--              <el-select v-model="formData.taskRunState" size="small" placeholder="请选择任务状态" class="searchItemWidth" clearable filterable>-->
<!--                <el-option label="运行中" :value="0"></el-option>-->
<!--                <el-option label="已完成" :value="1"></el-option>-->
<!--                <el-option label="异常中断" :value="2"></el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->

            <!-- <el-form-item label="数据来源" class="searchItem">
              <el-select v-model="formData.taskStatus" size="small" placeholder="请选择数据来源" class="searchItemWidth" clearable>
              </el-select>
            </el-form-item> -->
        </el-form>
      </el-row>
      <el-row>
        <el-button type="primary" icon="el-icon-plus" size="small" @click="addNewTask">新增任务</el-button>
        <el-button style="float:right; margin-left:20px;" size="small" @click="reset">重置</el-button>
        <el-button type="primary" @click="showAllItems = !showAllItems" size="small" style="float:right;">高级搜索</el-button>
        <el-button type="primary" icon="el-icon-search" size="small" @click="listSearch" style="float:right;">查询</el-button>
      </el-row>
    </el-card>
    <el-row style="margin-top:10px;">
      <el-table
       :data="tableData"
       size="small"
       tooltip-effect="dark"
       ref="table"
       :stripe="true"
       :border="true"
       style="width: 100%;"
       v-loading="loading"
        @expand-change="expandChange"
       max-height="550">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table size="mini" ref="subTableData" :data="expandPageMaps[props.row.taskFlowCode].tableData" key="saleOrder">
              <el-table-column
                prop="diagModelName"
                show-overflow-tooltip
                :resizable="false"
                label="诊断模型">
              </el-table-column>
              <el-table-column
                prop="createAt"
                show-overflow-tooltip
                :resizable="false"
                label="模型诊断启动时间">
                <template slot-scope="scope">
                    <span>{{scope.row.createAt | timeFlt}}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="diagModelState"
                show-overflow-tooltip
                :resizable="false"
                label="模型执行状态"
              width="100px">
                <template slot-scope="scope">
                  <el-tag type="success" v-if="scope.row.diagModelState === 1" size="small">诊断成功</el-tag>
                  <el-tag v-if="scope.row.diagModelState === 0" size="small">诊断中</el-tag>
<!--                  <el-tag type="warning" size="small">标签四</el-tag>-->
<!--                  diagErrInfo-->
                  <el-popover
                    placement="top-start"
                    title=""
                    width="200"
                    trigger="hover"
                    :content="'错误信息：' + (scope.row.diagErrInfo ? scope.row.diagErrInfo : '')">
                    <el-tag type="danger" v-if="scope.row.diagModelState === 2" size="small" slot="reference">诊断失败</el-tag>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column
                prop="picNum"
                show-overflow-tooltip
                :resizable="false"
                label="图片数量">
              </el-table-column>
              <el-table-column
                prop="defectivePicNum"
                width="120"
                :resizable="false"
                show-overflow-tooltip
                label="异常图片数量"/>
              <el-table-column
                prop="defectivePicNum"
                width="120"
                :resizable="false"
                show-overflow-tooltip
                label="缺陷总数"/>
              <el-table-column
                prop="status"
                show-overflow-tooltip
                :resizable="false"
                label="查看报告"
              width="80px">
                <template slot-scope="scope">
                  <el-button :title="(scope.row.diagModelState !== 1 || scope.row.defectivePicNum === 0) ? '任务正在进行或已失败或不存在异常图片，无法查看检测报告' : ''" type="text" @click="getReport(scope.row)" size="small" :disabled="scope.row.defectivePicNum === 0">查看报告</el-button>
                </template>
              </el-table-column>
              <el-table-column
                prop="status"
                show-overflow-tooltip
                :resizable="false"
                label="查看诊断详情"
                width="100px">
                <template slot-scope="scope">
                  <el-button :title="(scope.row.diagModelState !== 1 || scope.row.defectivePicNum === 0) ? '任务正在进行或已失败或不存在异常图片，无法查看检测报告' : ''" type="text" @click="goDetail(scope.row)" size="small" :disabled="scope.row.diagModelState !== 1 || scope.row.defectivePicNum === 0">查看诊断详情</el-button>
                </template>
              </el-table-column>
              <el-table-column
                prop="status"
                show-overflow-tooltip
                :resizable="false"
                label="查看诊断结果分析"
              width="180px">
                <template slot-scope="scope">
                  <el-button type="text" :title="(scope.row.diagModelState !== 1 || scope.row.defectivePicNum === 0) ? '任务正在进行或已失败或不存在异常图片，无法查看检测报告' : ''" @click="searchByType('按场站查询', props.row)" size="small" :disabled="scope.row.diagModelState !== 1 || scope.row.defectivePicNum === 0">按场站查询</el-button>
                  <el-button type="text" :title="(scope.row.diagModelState !== 1 || scope.row.defectivePicNum === 0) ? '任务正在进行或已失败或不存在异常图片，无法查看检测报告' : ''" @click="searchByType('按组件查询', props.row)" size="small" :disabled="scope.row.diagModelState !== 1 || scope.row.defectivePicNum === 0">按组件查询</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination class="text-center marginTop10" @current-change="current => expandCurrentChange(current, props.row)" :page-size="expandPageMaps[props.row.taskFlowCode].pageSize" :current-page.sync="expandPageMaps[props.row.taskFlowCode].currentPage" background layout="total, prev, pager, next, jumper" :total="expandPageMaps[props.row.taskFlowCode].total">
            </el-pagination>
          </template>
        </el-table-column>
       <el-table-column
         prop="taskStartTime"
         show-overflow-tooltip
         :resizable="false"
         width="140px"
         label="任务开始时间">
         <template slot-scope="scope">
             <span>{{scope.row.taskStartTime | timeFlt}}</span>
         </template>
       </el-table-column>
       <el-table-column
         prop="inspectTaskCode"
         show-overflow-tooltip
         :resizable="false"
         label="任务编码">
       </el-table-column>
       <el-table-column
         prop="oriFileName"
         show-overflow-tooltip
         :resizable="false"
         label="文件名称">
       </el-table-column>
       <el-table-column
         prop="fileDescribe"
         show-overflow-tooltip
         :resizable="false"
         label="文件描述">
       </el-table-column>
       <el-table-column
         prop="companyName"
         show-overflow-tooltip
         :resizable="false"
         label="单位">
       </el-table-column>
       <el-table-column
         prop="stationName"
         show-overflow-tooltip
         :resizable="false"
         label="场站">
       </el-table-column>
<!--       <el-table-column-->
<!--         show-overflow-tooltip-->
<!--         :resizable="false"-->
<!--         label="任务状态">-->
<!--         <template slot-scope="scope">-->
<!--           <span>-->
<!--             {{ scope.row.taskRunState === 0 ? '运行中' : scope.row.taskRunState === 1 ? '已完成' : '异常中断' }}-->
<!--           </span>-->
<!--         </template>-->
<!--       </el-table-column>-->
       <el-table-column
         show-overflow-tooltip
         :resizable="false"
         label="操作"
       width="140px">
         <template slot-scope="scope">
             <el-button type="text" href="javascript:void(0);" @click="modifyTask(scope.row)" size="small">修改</el-button>
             <el-button type="text" href="javascript:void(0);" @click="addTask(scope.row)" size="small">添加诊断任务</el-button>
         </template>
       </el-table-column>
      </el-table>
    </el-row>
    <el-pagination class="text-center marginTop10" @current-change="currentChange" :page-size="pageSize" :current-page.sync="page" background layout="total, prev, pager, next, jumper" :total="total">
    </el-pagination>
    <com-dialog-edit-task ref="dialogEditTask" @sendDialogEditTask="sendDialogEditTask"></com-dialog-edit-task>
    <com-dialog-modify-task ref="dialogModifyTask" :modifyTaskParams="modifyTaskParams" @sendDialogModifyTask="sendDialogModifyTask"></com-dialog-modify-task>
    <el-dialog :close-on-click-modal="false" title="查看检测报告" :visible.sync="imgVisible" width="1000px" @close="closeModal">
      <!-- <pdf
        style="width:100%; height:100%;"
        :src="src"
      /> -->
      <div class="reportContainer">
        <div>
          <div class="reportTitle">
            <p class="name">{{ report.title }}</p>
            <div class="reportInfo">
              <p>单位名称：{{ report.companyName }}</p>
              <p>场站名称：{{ report.stationName }}</p>
              <p>任务编号：{{ report.inspectTaskCode }}</p>
              <p>诊断任务编号：{{ report.diagTaskCode }}</p>
              <p>诊断模型：{{ report.diagModelName }}</p>
              <p>诊断时间：{{ report.diagDay }}</p>
              <p>图片总数：{{ report.totalPicNum }}</p>
              <p>故障图片数量：{{ report.totalDefectivePicNum }}</p>
              <p>故障总数：{{ report.totalDefectiveNum }}</p>
            </div>
          </div>
        </div>
        <p class="middle">
          缺陷位置
          <span style="float:right; color:#3977F3; cursor:pointer;" @click="downloadPdfs(report)"><i class="el-icon-download"></i>下载报告</span>
        </p>
        <div class="content">
          <div class="item" v-for="item in report.picAndLocationDTO">
            <div class="leftSide">
              <div v-for="(data, idx) in item.defectivePosition" class="leftItem">
                <p style="font-size:20px; font-weight:600; color:#37405E; margin-bottom:20px;">缺陷位置{{ idx + 1 }}：</p>
                <p style="line-height:30px;">
                  经纬度：{{ data.defectivePosition }}
                </p>
                <p style="line-height:30px;">
                  所在光伏组件编码：{{ data.pvModuleCode }}
                </p>
                <p style="line-height:30px;">
                  所在光伏组件中心经纬度：{{ data.centerLatLong }}
                </p>
              </div>
            </div>
            <div class="rightSide">
              <div class="leftItem">
                <p>{{ (report.diagModelName === '割草验收' ? '可见光图:' : '红外光图:') + item.dataResultPicName }}</p>
                <img :src="'data:image/jpeg;base64,' + item.dataResultPath" />
              </div>
<!--              <div class="rightItem" v-if="report.diagModelName !== '割草验收'">-->
<!--                <p>{{ "可见光图:" + item.visiblePicName }}</p>-->
<!--                <img :src="'data:image/jpeg;base64,' + item.visibleDataPath" />-->
<!--              </div>-->
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {parseTime} from "../../../utils/index";
  import myTaskApi from '../../../api/myTask'
  import stations from "../../../api/stations"
  // import dataSourceApi from "../../../api/dataSourceApi";
  import manual from "../../../api/manual";
  // import utils from "../../../utils/index";
  import moment from 'moment'
  import comDialogEditTask from "./components/dialogEditTask"
  import comDialogModifyTask from "./components/dialogModifyTask"
  import taskListApi from "../../../api/taskList";
  import dataSourceApi from "../../../api/dataSourceApi";
  import htmlToPdf from '../../../utils/generatePic'

  export default {
    name: 'myTask',
    components: {
      comDialogEditTask,
      comDialogModifyTask
    },
    data: () => ({
      loading: false,
      form: {
        inspectTaskCode: '',
        taskFlowCode: '',
        taskRunState: '',
        taskStartTime: []
      },
      imgVisible: false,
      formData: {
        oriFileName: "",
        companyCode: "",
        stationCode: "",
        taskNumber: "",
        taskRunState: "",
        remark: "",
        dataSource: 0,
        uploadTime: null,
        order: 'desc'
      },
      showAllItems: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      stationList: [],
      taskNumberList: [],
      page: 0,
      totalElements: 0,
      subTableData: [],
      newForm: {},
      rules: {},
      tree: [],
      fileList: [],
      file: null,
      dialogFormVisible: false,
      modifyTaskParams: {},
      expandPageMaps: {},
      report: {}
    }),
    mounted() {
      this.getCompanyList()
      // this.getMyTaskList()
      this.getTaskNumberByCompany()
      this.getList()
    },
    methods: {
      listSearch() {
        this.currentPage = 1
        this.getList()
      },
      getList() {
        this.expandPageMaps = {}
        this.loading = true
        myTaskApi.getList({
          page: this.currentPage,
          limit: this.pageSize,
          sidx: 'create_at',
          order: 'desc',
          oriFileName: this.formData.oriFileName,
          companyCode: this.formData.companyCode,
          stationCode: this.formData.stationCode,
          inspectTaskCode: this.formData.taskNumber,
          taskFlowCode: this.formData.taskFlowCode,
          taskRunState: this.formData.taskRunState,
          fileDescribe: this.formData.remark,
          startTime: this.formData.taskStartTime && this.formData.taskStartTime[0] ? moment(this.formData.taskStartTime[0]).format('YYYY-MM-DD HH:mm:ss') : '',
          endTime: this.formData.taskStartTime && this.formData.taskStartTime[1] ? moment(this.formData.taskStartTime[1]).format('YYYY-MM-DD HH:mm:ss') : ''
        }).then(res => {
          this.loading = false
          if (res && res.status === 200 && res.data.code === 200) {
            this.tableData = res.data.data.list || [{}]
            this.total = res.data.data.totalCount
            this.tableData.map(item => {
              this.$set(this.expandPageMaps, item.taskFlowCode, {
                currentPage: 1,
                page: 10,
                total: 0,
                tableData: [],
                expanded: false
              })
              // this.expandPageMaps[item.taskFlowCode] = {
              //   currentPage: 1,
              //   page: 10,
              //   total: 0,
              //   tableData: [],
              //   expanded: false
              // }
            })
          }
        }).catch(err => {
          this.loading = false
        })
      },
      modifyTask(row) {
        // this.formData = {
        //   inspectTaskCode: '',
        //   taskNumber: "",
        //   taskFlowCode: '',
        //   taskRunState: '',
        //   taskStartTime: []
        // }
        this.currentPage = 1
        this.modifyTaskParams = row
        this.$refs.dialogModifyTask.show()
      },
      reset() {
        this.formData = {
          companyCode: "",
          stationCode: "",
          taskNumber: "",
          dataSource: 0,
          uploadTime: null,
          order: 'desc'
        }
      },
      expandChange(row, expandedRows) {
        if (!row.taskFlowCode) return
        if (this.expandPageMaps[row.taskFlowCode].expanded) return
        myTaskApi.getTaskFlowDetail({
          limit: this.expandPageMaps[row.taskFlowCode].pageSize,
          page: this.expandPageMaps[row.taskFlowCode].currentPage,
          sidx: 'create_at',
          order: 'desc',
          taskFlowCode: row.taskFlowCode
        }).then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.expandPageMaps[row.taskFlowCode].expanded = true
            this.$set(this.expandPageMaps[row.taskFlowCode], 'tableData', res.data.data.list)
            this.$set(this.expandPageMaps[row.taskFlowCode], 'total', res.data.data.totalCount)
          }
        })
      },
      downloadPdfs(data) {
        if (!data) return
        htmlToPdf(data, this.html2canvas, this)
      },
      expandCurrentChange(currentPage, row) {
        this.expandPageMaps[row.taskFlowCode].currentPage = currentPage
        this.expandChange(row)
      },
      addNewTask() {
        this.$refs.dialogEditTask.show()
      },
      cancelSubmit() {
        this.dialogFormVisible = false
      },

      getCompanyList() {
        stations.getCompanyList().then(res => {
          if (res && res.data.code === 200) {
            this.tree = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      stationChange() {
        // this.getTaskNumberByCompany()
        this.formData.taskNumber = ""
      },
      companyChange() {
        this.formData.stationCode = ""
        this.formData.taskNumber = ""
        this.getStationByCompany()
      },
      taskNumberChange() {
        if (!this.formData.taskNumber) {
          this.formData.oriFileName = ""
          this.formData.remark = ""
          return
        }
        // 获取文件名和文件描述
        dataSourceApi.getNameAndRemarkInfo({inspectTaskCode: this.formData.taskNumber}).then(data => {
          this.$nextTick(() => {
            this.formData.oriFileName = data.data.data.oriFileName
            this.formData.remark = data.data.data.remark
          })
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      getTaskNumberByCompany() {
        manual.listInspectTaskCode({
          companyCode: this.formData.companyCode,
          stationCode: this.formData.stationCode
        }).then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.taskNumberList = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      getStationByCompany() {
        manual.getStationByCompany({
          companyCode: this.formData.companyCode
        }).then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.stationList = res.data.data
          }
        }).catch(e => {
          this.$message.error({message: e.message ? e.message : e, center: true})
        })
      },
      // 分页方法
      // sizeChange(val) {
      //   this.pageSize = val
      //   this.getMyTaskList()
      // },
      currentChange(val) {
        this.currentPage = val
        this.getList()
      },
      preview(imgRef) {
        this.$refs[imgRef].clickHandler()
      },
      reset() {
        this.formData = {
          page: 1,
          limit: 10,
          dataSource: 0,
          sidx: 'create_at',
          oriFileName: "",
          companyCode: "",
          stationCode: "",
          taskNumber: "",
          taskRunState: "",
          remark: "",
          dataSource: 0,
          uploadTime: null,
          order: 'desc'
        }
        this.tableData = []
      },
      sendDialogModifyTask() {
        this.getList()
      },
      sendDialogEditTask() {
        this.getList()
      },
      addTask(row) {
        this.$router.push({
          path: "/diagnosticTask/startTask/index",
          query: row
        })
      },
      closeModal() {
        this.imgVisible = false
      },
      getReport(row) {
        taskListApi.getReport({
          diagTaskCode: row.diagTaskCode,
          diagModelCode: row.diagModelCode
        }).then(res => {
          if (res && res.status === 200 && res.data.code === 200) {
            this.imgVisible = true
            this.report = {
              ...res.data.data,
              diagModelCode: row.diagModelCode
            }
          } else {
            this.$message.error(res.data.message)
          }
        }).catch(err => {
          this.$message.error('接口请求失败！')
        })
      },
      goDetail(row) {
        this.$router.push({
          path: '/taskResult/resultDetail/index',
          query: {
            inspectTaskCode: row.inspectTaskCode,
            diagTaskCode: row.diagTaskCode,
            diagModelCode: row.diagModelCode
          }
        })
      },
      searchByType(type, row) {
        this.$router.push({
          path: '/taskResult/getResult/index',
          query: {
            type,
            ...row
          }
        })
      },
    }
  }
</script>
<style lang="scss">
.background{
  /*background-color: rgba(0,58,102,0.6);*/
  padding:10px 20px;
}
.myTask{
  .searchLine{
    .searchItem{
      display: inline-block;
      vertical-align: top;
    }
    .el-form-item{
      margin-bottom: 3px !important;
    }
    .bigItem{
      width: 100%;
    }
  }
  .pagination{
    text-align: center;
    margin-top: 20px;
  }
  .el-dialog__body{
    padding: unset;
  }
  .title{
    font-weight: bold;
    color: #3977F3;
    background:rgba(57, 119, 243, .1);
    line-height:40px;
    padding-left: 21px;
    margin-bottom: 10px;
  }
  .reportContainer {
    background:#fff;
    padding:100px;
    padding-top:0px;
    padding-bottom:100px;
    font-family: 'Microsoft YaHei';
    box-sizing:border-box;
    // .icon{
    //   width:250px;
    //   margin-right:50px;
    //   vertical-align:top;
    //   color:#000;
    // }
    .reportTitle{
      width:100%;
      display:inline-block;
      .name{
        margin-bottom: 20px;
        color:#37405E;
        font-size:50px;
        font-weight:bold;
        text-align: center;
        line-height: 100px;
      }
      .reportInfo{
        color:#000;
        font-size:18px;
        background:#f5f5f5;
        padding:20px;
        padding-left:20px;
        font-family:'Microsoft YaHei';
        // font-weight: bold;
        color:#616161;
        padding-left: 60px;
        line-height: 30px;
      }
    }
    .middle{
      color:#37405E;
      font-size:25px;
      font-weight:bold;
      margin-top:30px;
      margin-bottom:20px;
    }
    .content{
      width:100%;
      border-top:2px solid #e4e4e4;
      border-right:2px solid #e4e4e4;
      .item{
        width: 100%;
        position: relative;
        padding-right: 489px;
        border-bottom:2px solid #e4e4e4;
        border-left:2px solid #e4e4e4;
      }
      .leftSide{
        width: 390px;
        border-right: 2px solid #e4e4e4;
        min-height: 400px;
        .leftItem{
          padding: 20px;
          font-size: 18px;
        }
      }
      .rightSide{
        width:350px;
        position: absolute;
        right: 0;
        top:0;
        display:inline-block;
        vertical-align:top;
        padding:25px;
        .leftItem,.rightItem{
          display: inline-block;
          vertical-align: top;
          width:99%;
          >p{
            font-size:18px;
            color:#616161;
            margin-bottom: 10px;
            line-height: 26px;
          }
          >img{
            width:300px; height:300px;
          }
        }
        .leftItem{
          padding-right: 20px;
        }
        .rightItem{
          padding-left: 20px;
        }
      }
    }
  }
}
</style>
